package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Log;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;

//ship改地址后或者直接确认地址后，若确认订单，则转到展示订单的界面
public class OrderServlet extends HttpServlet {
    private static final String VIEW_ORDER = "/WEB-INF/jsp/order/ViewOrder.jsp";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        CatalogService catalogService = new CatalogService();

        Account account = (Account) session.getAttribute("account");
        //获得最终确定order的信息
        Order order = (Order) session.getAttribute("order");
        //set在session中的order的line item
        session.setAttribute("lineItems",order.getLineItems());
        //插入订单信息
        OrderService orderService = new OrderService();
        orderService.insertOrder(order);
        // 重置购物车，并重置session中的值
        catalogService.deleteCartByUsername(account.getUsername());

        //时间
        SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String datetime = tempDate.format(new java.util.Date());
        //信息
        String info = "用户"+account.getUsername()+"确认提交订单";
        Log log = new Log(account.getUsername(),datetime,info);
        //添加log
        new AccountService().addLog(log);


        request.getRequestDispatcher(VIEW_ORDER).forward(request,response);
    }
}